package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 设备Service业务层处理
 *
 * @author success
 * @date 2025-01-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 获取产品列表
     */
    @Override
    public void syncProductList() {
        // 请求参数
        QueryProductListRequest request = new QueryProductListRequest();
        request.setCurrentPage(1);
        request.setPageSize(100);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        // 调用第三方查询产品列表
        QueryProductListResponse response;
        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 判断，如果数据为空，则中断请求
        if (!response.body.success) {
            throw new RuntimeException("同步产品列表失败");
        }

        // 存储到redis
        String jsonStr = JSONUtil.toJsonStr(response.body.data.list.productInfo);

        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST, jsonStr);
    }

    /**
     * 获取产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> getProductList() {
        // 1. 从redis中获取产品列表
        String productListStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);
        // 如果数据为空，则返回一个空集合
        if (StringUtils.isEmpty(productListStr)) {
            return Collections.emptyList();
        }

        // 2.返回数据
        return JSONUtil.toList(productListStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        // 判断设备名称是否重复
        Long count = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count > 0) {
            throw new BaseException("设备名称已存在，请重新输入");
        }

        // 保存设备到iot平台
        RegisterDeviceRequest request = deviceDto.getRegisterDeviceRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse response;
        try {
            response = client.registerDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }

        // 判断保存设备到iot平台是否成功
        if (!response.getBody().success) {
            throw new RuntimeException(response.getBody().getErrorMessage());
        }

        // 物理位置
        if (deviceDto.getLocationType().equals(0)) {
            deviceDto.setPhysicalLocationType(-1);
        }

        // 补全设备id
        String iotId = response.getBody().getData().getIotId();

        // 设置产品名称到设备对象
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(iotId);

        try {
            int result = deviceMapper.insert(device);
            if (result == 0) {
                deleteIOTDevice(deviceDto, iotId);
                throw new BaseException("该老人/位置已绑定该产品，请重新选择");
            }
        } catch (Exception e) {
            deleteIOTDevice(deviceDto, iotId);
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
    }

    /**
     * 删除iot中的设备
     *
     * @param deviceDto
     * @param iotId
     */
    private void deleteIOTDevice(DeviceDto deviceDto, String iotId) {
        // 删除iot中的设备
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.setDeviceName(deviceDto.getDeviceName());
        deleteDeviceRequest.setProductKey(deviceDto.getProductKey());
        deleteDeviceRequest.setIotId(iotId);
        deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        try {
            client.deleteDevice(deleteDeviceRequest);
        } catch (Exception ex) {
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }
    }

    /**
     * 查询设备详情
     *
     * @param deviceDto
     * @return
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        // 查询iot平台中的设备数据
        QueryDeviceDetailRequest queryDeviceDetailRequest = new QueryDeviceDetailRequest();
        queryDeviceDetailRequest.setIotId(deviceDto.getIotId());
        queryDeviceDetailRequest.setProductKey(deviceDto.getProductKey());
        queryDeviceDetailRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(queryDeviceDetailRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备，调用失败");
        }
        // 安全校验
        if (!response.getBody().success) {
            throw new RuntimeException("物联网接口 - 查询设备，调用失败");
        }

        // 查询表中的数据
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));

        DeviceVo deviceVo = BeanUtil.toBean(device, DeviceVo.class);

        // 合并
        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = response.getBody().getData();
        BeanUtil.copyProperties(data, deviceVo, CopyOptions.create().ignoreNullValue());
        return deviceVo;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param
     */
    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询物模型数据，调用失败");
        }

        if (!response.body.success) {
            throw new BaseException(response.body.errorMessage);
        }

        return AjaxResult.success(response.body.data);
    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param request@return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询物模型数据，调用失败");
        }

        if (!response.body.success) {
            throw new RuntimeException(response.body.errorMessage);
        }

        return AjaxResult.success(response.body.data);
    }

    /**
     * 更新设备信息
     *
     * @param device
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDevice(Device device) {
        int result = deviceMapper.updateById(device);

        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> deviceNicknameInfo = new ArrayList<>();

        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo nicknameInfo = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        nicknameInfo.setProductKey(device.getProductKey());
        nicknameInfo.setDeviceName(device.getDeviceName());
        nicknameInfo.setNickname(device.getNickname());

        request.setDeviceNicknameInfo(deviceNicknameInfo);

        deviceNicknameInfo.add(nicknameInfo);

        request.setDeviceNicknameInfo(deviceNicknameInfo);

        BatchUpdateDeviceNicknameResponse response;
        try {
            response = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 更新设备信息，调用失败");
        }

        if (!response.body.success) {
            throw new BaseException(response.body.errorMessage);
        }

        return result;
    }

    /**
     * 删除设备信息
     *
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDevice(DeleteDeviceRequest request) {
        // 1.删除数据库中的数据
        deviceMapper.delete(Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, request.getIotId())
                .eq(Device::getProductKey, request.getProductKey()));

        // 2.删除物联网平台的设备信息
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        DeleteDeviceResponse response;

        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 删除设备信息，调用失败");
        }

        if (!response.body.success) {
            throw new BaseException(response.body.errorMessage);
        }
    }
}
